/*
 * COPYRIGHT. ShenZhen iByte Technology Co., Ltd. 2018.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen iByte Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * Nov 30, 2018    Li.shangzhi         Create the class
 */
package com.github.icloud.elasticsearch;

import java.net.InetAddress;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;

import com.github.icloud.elasticsearch.comm.ElasticSearchConstants;
import com.github.icloud.elasticsearch.util.Utils;
/**
 * @FileName ElasticsearchClient.java
 * @Description: Elasticsearch 客户端
 *
 * @Date Nov 30, 2018 11:27:51 AM
 * @author Li.shangzhi
 * @version 1.0
 */
public class ElasticsearchClient {

	protected TransportClient client;

	@SuppressWarnings("resource")
	@Before
	public void setUp() throws Exception {

		Settings esSettings = Settings.builder()
				.put("cluster.name",ElasticSearchConstants.elasticsearch_clusterName)  	//设置ES实例的名称
				.put("client.transport.sniff", true)   //自动嗅探整个集群的状态，把集群中其他ES节点的ip添加到本地的客户端列表中
				.build();
		/**
		 * 这里的连接方式指的是没有安装x-pack插件,如果安装了x-pack则参考{@link ElasticsearchXPackClient}
		 * 1. java客户端的方式是以tcp协议在9300端口上进行通信
		 * 2. http客户端的方式是以http协议在9200端口上进行通信
		 */
		client = new PreBuiltTransportClient(esSettings)
		.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ElasticSearchConstants.elasticsearch_InetAddress),
				ElasticSearchConstants.elasticsearch_Port));

		System.out.println("ElasticsearchClient 连接成功");
	}

	@After
	public void tearDown() throws Exception {
		if (client != null) {
			client.close();
		}

	}

	protected void println(SearchResponse searchResponse) {
		Utils.println(searchResponse);
	}

}
